/*
 * @Description: mysql 实例对象
 * @Autor: zzzzzed
 * @Date: 2023-11-01 17:10:09
 * @LastEditors: zzzzzed
 */

const mysql = require("mysql");

export class MySql {
    private _connecntor: any = null;
    private _options: any = null;
    constructor() {
        // this.init();
    }

    public init(args: IMySqlConnectOptions): MySql {
        this._options = args;
        this._connecntor = mysql.createConnection(args);

        try {
            // 连接数据库
            this._connecntor.connect();
        } catch (error) {
            this.logError(error);
        }

        return this;
    }

    /**
     * 执行sql查询
     */
    public query(sql: string): void {
        if (!this._connecntor) return;
        this._connecntor.query(sql, (err: any, result: any) => {
            if (err) {
                this.logError(err);
            } else {
                this.log(result);
            }
        });
    }

    private logError(error: any): void {
        console.log("【MySql】【error】", JSON.stringify(error));
    }

    private log(msg: any): void {
        console.log("【MySql】【info】", JSON.stringify(msg));
    }
}

export interface IMySqlConnectOptions {
    host: string,
    user: string,
    password: string,
    database: string,
}